package com.chj.exchange.topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 所有的课程内容
 */
public class AllConsumer {
    public static void main(String[] argv) throws IOException,InterruptedException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.200.169.5");
        factory.setVirtualHost("chj_vhost");
        factory.setUsername("chj");
        factory.setPassword("123456");
        // 打开连接和创建频道，与发送端一样
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare(TopicProducer.EXCHANGE_NAME,BuiltinExchangeType.TOPIC);
        // 声明一个随机队列
        String queueName = channel.queueDeclare().getQueue();
        //TODO  #  绑定所有队列
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "#");
        // TODO 关注所有的 B 章节
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "#.B");
        // TODO 关注所有的 kafka 课程
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME,"#.kafka.#");
        // TODO 关注chj01的所有课程
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "chj01.#");
        // TODO 关注chj01的所有的A章节
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "chj01.*.A");
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "chj01.#.A");
        // TODO 关注chj01的kafka的A章节
        channel.queueBind(queueName,TopicProducer.EXCHANGE_NAME, "chj01.kafka.A");

        System.out.println(" [*] Waiting for messages:");
        // 创建队列消费者
        final Consumer consumerA = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,Envelope envelope,
                                       AMQP.BasicProperties properties,byte[] body)throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" AllConsumer Received "+ envelope.getRoutingKey()+ "':'" + message + "' channel=="+channel.getChannelNumber());
            }
        };
        // 消息确认
        channel.basicConsume(queueName, true, consumerA);
    }

}
